package com.xxh.myapp.controller;



import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxh.myapp.entity.Student;
import com.xxh.myapp.entity.Teacher;
import com.xxh.myapp.entity.User;
import com.xxh.myapp.entity.wrapper.UserWrapper;
import com.xxh.myapp.msg.ReturnMsg;
import com.xxh.myapp.service.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.List;
import java.util.UUID;

/**
 * (User)表控制层
 *
 * @author makejava
 * @since 2020-05-01 16:33:32
 */
@RestController
@RequestMapping("user")
public class UserController extends ApiController {

    //图片上传路径
    @Value("${xxh.uploadPath}")
    String filePath ;//

    //服务器IP或者域名
    @Value("${ImagesbaseUrl}")
    String serUrl;

    //服务器端口号
    @Value("${server.port}")
    String serport;
    /**
     * 服务对象
     */
    @Resource
    private UserService userService;

    @Resource
    private StudentService studentService;
    @Resource
    private DeptService deptService;
    @Resource
    private StuclService stuclService;
    @Resource
    private ScoreService scoreService;
    @Resource
    private CourseService courseService;
    @Resource
    private TeacherService teacherService;

    /**
     * 分页查询所有数据
     *
     * @param page 分页对象
     * @param user 查询实体
     * @return 所有数据
     */
    @GetMapping
    public R selectAll(Page<User> page, User user) {
        return success(this.userService.page(page, new QueryWrapper<>(user)));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public R selectOne(@PathVariable Serializable id) {
        return success(this.userService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param user 实体对象
     * @return 新增结果
     */
    @PostMapping
    public R insert(@RequestBody User user) {
        return success(this.userService.save(user));
    }

    /**
     * 修改数据
     *
     * @param user 实体对象
     * @return 修改结果
     */
    @PutMapping
    public R update(@RequestBody User user) {
        return success(this.userService.updateById(user));
    }

    /**
     * 删除数据
     *
     * @param idList 主键结合
     * @return 删除结果
     */
    @DeleteMapping
    public R delete(@RequestParam("idList") List<Long> idList) {
        return success(this.userService.removeByIds(idList));
    }

    //用户登录操作
    @GetMapping("/login")
    public ReturnMsg UserLogin(String email, String psw,int role){
        ReturnMsg returnMsg = new ReturnMsg();
        QueryWrapper<User>queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("email",email);
        queryWrapper.eq("type",role);
        User dbuser = userService.getOne(queryWrapper);
        if(dbuser==null){
            returnMsg.setCode(100);
            returnMsg.setMsg("用户不存在，请注册");
            return returnMsg;
        }else {
            if(!dbuser.getUpassword().equals(psw)){
                returnMsg.setCode(101);
                returnMsg.setMsg("密码错误");
                return returnMsg;
            }else {
                returnMsg.setCode(200);
                returnMsg.setMsg("登录成功");
                return  returnMsg;
            }
        }
    }

    //用户注册操作
    @PostMapping("/register")
    public ReturnMsg Register(@RequestBody User user) {

        ReturnMsg returnMsg = new ReturnMsg();
        QueryWrapper<User>queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("email",user.getEmail());
        User dbuser = userService.getOne(queryWrapper);

        //判断用户是否存在
        if(dbuser!=null){
            returnMsg.setCode(102);
            returnMsg.setMsg("用户邮箱已经存在,换一个吧");
            return returnMsg;
        }else {
            //判断用户输入的学号，工号是否存在，否则不予注册
            switch (user.getType()){
                //学生
                case 1:
                    Student student = studentService.getById(user.getPno());
                    if(student==null){
                        returnMsg.setCode(-9);
                        returnMsg.setMsg("输入的学号不存在！你不是本校学生");
                        return  returnMsg;
                    }else {
                        userService.save(user);
                        returnMsg.setCode(200);
                        returnMsg.setMsg(returnMsg.getMsg()+":注册成功");
                        return  returnMsg;
                    }
                    //老师
                case 2:
                    Teacher teacher = teacherService.getById(user.getPno());
                    if(teacher==null){
                        returnMsg.setCode(-9);
                        returnMsg.setMsg("输入的工号号不存在！你不是本校老师");
                        return  returnMsg;
                    }else {
                        userService.save(user);
                        returnMsg.setCode(200);
                        returnMsg.setMsg(returnMsg.getMsg()+":注册成功");
                        return  returnMsg;
                    }
                    //管理员
                case 3:
                    returnMsg.setCode(-9);
                    returnMsg.setMsg("你以为我会开放管理员注册吗？太天真了");
                    return  returnMsg;
            }
            return null;
        }
    }

    //根据邮箱拿到用户信息
    @GetMapping("/getByEmail")
    public User getUserByEmail(String email){
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("email", email);
        User user = userService.getOne(userQueryWrapper);
        return user;
    }

    //图片上传的接口（测试用）,上传完成后更新图片URL
    @PostMapping("/postImage")
    public ReturnMsg upLoadImage(String email,@RequestParam(value = "upload") MultipartFile file){
        ReturnMsg returnMsg = new ReturnMsg();
        System.out.println(filePath);
        if(file.isEmpty()){
            returnMsg.setCode(-1);
            returnMsg.setMsg("文件为空");
            return returnMsg;
        }
        String fileName = file.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        fileName = UUID.randomUUID() + suffixName; // 新文件名(避免重复名字)

        String imageurl=serUrl+":"+serport+"/images/"+fileName; //图片的访问路径
        System.out.println(imageurl);

        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);

            //更新用户的头像URL
            UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
            userUpdateWrapper.eq("email",email);
            userUpdateWrapper.set("headimg",imageurl);
            userService.update(userUpdateWrapper);
            returnMsg.setMsg("文件上传成功！");
            returnMsg.setCode(200);
            return returnMsg;

        } catch (IOException e) {
            e.printStackTrace();
            returnMsg.setMsg("文件上失败！"+e.toString());
            returnMsg.setCode(-3);
            return returnMsg;
        }
    }

    //根据邮箱，拿到用户个人信息，显示到个人信息界面头部
    @GetMapping("/getUserInfo")
    public UserWrapper getUser(String email){
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("email", email);
        User user = userService.getOne(userQueryWrapper);
        UserWrapper header = new UserWrapper();
        header.setUser(user);
        Integer pno = user.getPno();
        switch (user.getType()){
            case 1:
                header.setTypeName("学生");
                Student student = studentService.getById(pno);
                header.setRealName(student.getSname());
                break;
            case 2:
                header.setTypeName("教师");
                Teacher teacher = teacherService.getById(pno);
                header.setRealName(teacher.getTname());
                break;
            case 3:
                header.setTypeName("管理员");
                header.setRealName("管理员不需要姓名");
                break;
        }

        return header;
    }

    


}